package sharetime.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

public class StringUtils {
	/**
	 * 规整的办法：把\替换成为\\,把|替换成为\|；这件事情是由JavaScript完成的
	 * 
	 * @param raw
	 *            WEB传过来的字符串
	 * @return 分解并还原后的结果
	 */
	public static String[] deformatWebString(String raw) {
		StringBuilder sb = new StringBuilder();
		ArrayList<String> list = new ArrayList<String>();
		for (int i = 0; i < raw.length(); i++) {
			char c = raw.charAt(i);
			switch (c) {
			case '\\':
				if (i == raw.length() - 1) {
					sb.append('\\');
					break;
				}
				char cc = raw.charAt(i + 1);
				if (cc == '|' || cc == '\\') {
					sb.append(cc);
					i++;
				} else {
					sb.append('\\');
				}
				break;
			case '|':
				list.add(sb.toString());
				sb.setLength(0);
				break;
			default:
				sb.append(c);
			}
		}
		list.add(sb.toString());
		return list.toArray(new String[0]);
	}

	public static String encodeURL(String s)
			throws UnsupportedEncodingException {
		return URLEncoder.encode(s, "UTF-8");
	}

	/**
	 * " => \" , \ => \\
	 * 
	 * @param s
	 * @return
	 */
	public static String escapeJson(String s) {
		if (s == null) {
			return null;
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}// for
		return sb.toString();
	}

	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 判断字符串中是否包含中文字符
	 * 
	 * @param str
	 * @return
	 */
	public static boolean containsChinese(String str) {
		String pattern = ".*[\\u4e00-\\u9fa5]+.*";
		return str.matches(pattern);
	}
}
